//
//  BLInfoPhotosViewController.m
//  Byelone
//
//  Created by Qi Liu on 2021/1/31.
//

#import "BLInfoPhotosViewController.h"
#import "TZImagePickerController.h"
#import "UIView+Layout.h"
#import <Photos/Photos.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "TZImageManager.h"
#import "TZVideoPlayerController.h"
#import "TZPhotoPreviewController.h"
#import "TZGifPhotoPreviewController.h"
#import "TZLocationManager.h"
#import "BLGridViewFlowLayout.h"
#import "BLPhotosCell.h"
#import "BLPhotosFootView.h"

#import "BLInfoPhotoWallController.h"

@interface BLInfoPhotosViewController ()<UICollectionViewDelegate,
UICollectionViewDataSource,
TZImagePickerControllerDelegate,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate>{
    NSMutableArray *_selectedPhotos;
    NSMutableArray *_selectedAssets;
    BOOL _isSelectOriginalPhoto;
    CGFloat _itemWH;
    CGFloat _margin;
}

@property (strong, nonatomic)  UICollectionView *itemView;
@property (strong, nonatomic) BLGridViewFlowLayout *layout;
@property (nonatomic,strong) BLPhotosFootView * sectionView;
@property (strong, nonatomic)  UIView *baseView;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (nonatomic, strong) NSOperationQueue *operationQueue;

@end

@implementation BLInfoPhotosViewController
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (@available(iOS 9, *)) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
 
    }
    return _imagePickerVc;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"图片编辑";
    _selectedPhotos = [NSMutableArray array];
    _selectedAssets = [NSMutableArray array];
    _maxSelected = 6;
    [self configUI];
}

-(void)configUI{
    // 如不需要长按排序效果，将LxGridViewFlowLayout类改成UICollectionViewFlowLayout即可
    _layout = [[BLGridViewFlowLayout alloc] init];
    CGRect frame = CGRectMake(0, 0, BL_WINDOW_WIDTH, BL_WINDOW_HEIGHT);
    UICollectionView * itemView = [[UICollectionView alloc]initWithFrame:frame collectionViewLayout:_layout];
    CGFloat rgb = 244 / 255.0;
    _itemView = itemView;
    _itemView.alwaysBounceVertical = YES;
    _itemView.delegate = self;
    _itemView.dataSource = self;
    _itemView.backgroundColor = [UIColor colorWithRed:rgb green:rgb blue:rgb alpha:1.0];
    _itemView.contentInset = UIEdgeInsetsMake(4, 4, 4, 4);
    _itemView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [_itemView registerClass:[BLPhotosCell class] forCellWithReuseIdentifier:@"BLPhotosCell"];
    [_itemView registerNib:[UINib nibWithNibName:@"BLPhotosFootView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"BLPhotosFootView"];
    [_itemView registerNib:[UINib nibWithNibName:@"BLPhotosFootView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"BLPhotosFootView"];
    [self.view addSubview:_itemView];
    [_itemView reloadData];
    
    
//    导航栏又按钮
//    UIButton *btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
//    [btnRight setTitle:@"预览" forState:UIControlStateNormal];
//    [btnRight setTitleColor:[UIColor chColorWithHexString:@"#6C72F5"] forState:UIControlStateNormal];
//    [btnRight addTarget:self action:@selector(clickRightBar) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:btnRight];
//    self.navigationItem.rightBarButtonItem = item;
}
- (void)clickRightBar{
    BLInfoPhotoWallController *vc = [[BLInfoPhotoWallController alloc]init];
    vc.blockPhotoWall = self.blockPhoto;
    vc.isFromPic = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    NSInteger contentSizeH = 14 * 35 + 20;
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        self.scrollView.contentSize = CGSizeMake(0, contentSizeH + 5);
//    });
    
    _margin = 4;
    _itemWH = (self.view.tz_width - 2 * _margin - 4) / 3 - _margin;
    _layout.itemSize = CGSizeMake(_itemWH, _itemWH);
    _layout.minimumInteritemSpacing = _margin;
    _layout.minimumLineSpacing = _margin;
    [self.itemView setCollectionViewLayout:_layout];

}

#pragma mark UICollectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (_selectedPhotos.count >= self.maxSelected) {
        return _selectedPhotos.count;
    }
//    if (!self.allowPickingMuitlpleVideoSwitch.isOn) {
//        for (PHAsset *asset in _selectedAssets) {
//            if (asset.mediaType == PHAssetMediaTypeVideo) {
//                return _selectedPhotos.count;
//            }
//        }
//    }
    return _selectedPhotos.count + 1;
}


-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(12, 0, 20, 0);
}


-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(collectionView.frame.size.width, 40);
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(collectionView.frame.size.width, 80);
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        BLPhotosFootView *view =  [collectionView dequeueReusableSupplementaryViewOfKind :UICollectionElementKindSectionHeader withReuseIdentifier:@"BLPhotosFootView"   forIndexPath:indexPath];
        view.isFoot = NO;
        _sectionView = view;
        return view;

    }else{
        BLPhotosFootView *view =  [collectionView dequeueReusableSupplementaryViewOfKind :UICollectionElementKindSectionFooter   withReuseIdentifier:@"BLPhotosFootView"   forIndexPath:indexPath];
        [view.saveBtn addTarget:self action:@selector(photoSave:) forControlEvents:UIControlEventTouchUpInside];
        view.isFoot = YES;
        return view;
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BLPhotosCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BLPhotosCell" forIndexPath:indexPath];
//    cell.videoImageView.hidden = YES;
    if (indexPath.item == _selectedPhotos.count) {
        cell.imageView.hidden = YES;
        cell.deleteBtn.hidden = YES;
        cell.gifLable.hidden = YES;
    } else {
        cell.imageView.hidden = NO;
        cell.imageView.image = _selectedPhotos[indexPath.item];
        cell.asset = _selectedAssets[indexPath.item];
        cell.deleteBtn.hidden = NO;
    }
    cell.gifLable.hidden = YES;
    cell.deleteBtn.tag = indexPath.item;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == _selectedPhotos.count) {
        [self pushTZImagePickerController];
    }else{
        
        PHAsset *asset = _selectedAssets[indexPath.item];
        BOOL isVideo = NO;
        isVideo = asset.mediaType == PHAssetMediaTypeVideo;
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:_selectedPhotos index:indexPath.item];
        imagePickerVc.maxImagesCount = self.maxSelected;
        imagePickerVc.allowPickingGif = NO;
//        imagePickerVc.autoSelectCurrentWhenDone = NO;
        imagePickerVc.allowPickingOriginalPhoto = NO;
        imagePickerVc.allowPickingMultipleVideo = NO;
        imagePickerVc.showSelectedIndex = YES;
        imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
        imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            self->_selectedPhotos = [NSMutableArray arrayWithArray:photos];
            self->_selectedAssets = [NSMutableArray arrayWithArray:assets];
            self->_isSelectOriginalPhoto = isSelectOriginalPhoto;
            [self->_itemView reloadData];
            self->_itemView.contentSize = CGSizeMake(0, ((self->_selectedPhotos.count + 2) / 3 ) * (self->_margin + self->_itemWH));
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    }
}
#pragma mark - TZImagePickerController

- (void)pushTZImagePickerController {
    if (self.maxSelected <= 0) {
        return;
    }
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.maxSelected columnNumber:4 delegate:self pushPhotoPickerVc:YES];
#pragma mark - 五类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    
    if (self.maxSelected > 1) {
        // 1.设置目前已经选中的图片数组
        imagePickerVc.selectedAssets = _selectedAssets; // 目前已经选中的图片数组
    }
//    imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮
//    imagePickerVc.allowTakeVideo = NO;   // 在内部显示拍视频按
    imagePickerVc.videoMaximumDuration = 10; // 视频最大拍摄时间
    [imagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    // 设置竖屏下的裁剪尺寸
    NSInteger left = 30;
    NSInteger widthHeight = self.view.tz_width - 2 * left;
    NSInteger top = (self.view.tz_height - widthHeight) / 2;
    imagePickerVc.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
    imagePickerVc.scaleAspectFillCrop = YES;
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    imagePickerVc.showSelectedIndex = YES;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {

    }];
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark - LxGridViewDataSource

/// 以下三个方法为长按排序相关代码
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath.item < _selectedPhotos.count;
}

- (BOOL)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath canMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    return (sourceIndexPath.item < _selectedPhotos.count && destinationIndexPath.item < _selectedPhotos.count);
}

- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath didMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    UIImage *image = _selectedPhotos[sourceIndexPath.item];
    [_selectedPhotos removeObjectAtIndex:sourceIndexPath.item];
    [_selectedPhotos insertObject:image atIndex:destinationIndexPath.item];
    
    id asset = _selectedAssets[sourceIndexPath.item];
    [_selectedAssets removeObjectAtIndex:sourceIndexPath.item];
    [_selectedAssets insertObject:asset atIndex:destinationIndexPath.item];
    [_itemView reloadData];
}
#pragma mark - TZImagePickerControllerDelegate
/// User click cancel button
/// 用户点击了取消
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    // NSLog(@"cancel");
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    _selectedPhotos = [NSMutableArray arrayWithArray:photos];
    _selectedAssets = [NSMutableArray arrayWithArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    [_itemView reloadData];
    // 3. 获取原图的示例，用队列限制最大并发为1，避免内存暴增
    self.operationQueue = [[NSOperationQueue alloc] init];
    self.operationQueue.maxConcurrentOperationCount = 1;
    self.sectionView.photoCount.text = [NSString stringWithFormat:@"%lu/%ld",(unsigned long)_selectedPhotos.count,(long)_maxSelected];
}

-(void)uploadImage{

    [BLTool upLoadImageArray:_selectedPhotos type:UpLoadImageType_Photowall success:^(NSArray * _Nonnull urlArray) {
        NSLog(@"上传图片的回调链接：%@",urlArray);
        [self uploadUrlArray:urlArray];
    } failure:^(NSString * _Nonnull errorString) {
        
    }];
    
//    [BLTool upLoadImageArray:_selectedPhotos isPortrait:NO success:^(NSArray * _Nonnull urlArray) {
//        NSLog(@"上传图片的回调链接：%@",urlArray);
//        [self uploadUrlArray:urlArray];
//    } failure:^(NSString * _Nonnull errorString) {
//        
//    }];
}

-(void)uploadUrlArray:(NSArray *)urlArray{
    
    NSDictionary * dic =  @{@"photoList":urlArray};

    
//    NSDictionary * dic =  @{@"photoList":@[
//                                    @{@"photoPath": @"https%3A%2F%2Fbyelone-test.oss-cn-beijing.aliyuncs.com%2F7606839875589%2Fphotowall%2F1c285b7262cb49198a63b9e8533cc846.JPG",
//                                      @"weight": @(200),
//                                      @"height": @(200)}
//
//    ]};

    
//    [BLHttpTool postJson:BL_USER_SETPHOTOLIST params:dic successBlock:^(NSDictionary * _Nonnull obj) {
//        NSLog(@"++++++%@",obj);
//    } failedBlock:^(NSError * _Nonnull error) {
//        NSLog(@"----%@",error);
//    }];
    
    //415
    [BLHttpTool postJson:BL_USER_SETPHOTOLIST params:dic successBlock:^(NSDictionary * _Nonnull obj) {
        NSLog(@"postWithPath++++++%@",obj);
        
        
        [HUD showtip:@"图片上传成功"];
        
        if (self->_blockPhoto) {
            self->_blockPhoto();
        }
        
        [self.navigationController popViewControllerAnimated:YES];
        
    } failedBlock:^(NSError * _Nonnull error) {
        NSLog(@"postWithPath----%@",error);
    }];
//    [BLHttpTool postWithPath:BL_USER_SETPHOTOLIST params:dic successBlock:^(NSDictionary * _Nonnull obj) {
//        NSLog(@"postWithPath++++++%@",obj);
//    } failedBlock:^(NSURLSessionDataTask * _Nonnull data, NSError * _Nonnull error) {
//        NSLog(@"postWithPath----%@",error);
//    }];
    
}


// 决定相册显示与否
- (BOOL)isAlbumCanSelect:(NSString *)albumName result:(PHFetchResult *)result {
    return YES;
}
// 决定asset显示与否
- (BOOL)isAssetCanBeDisplayed:(PHAsset *)asset {
    return YES;
}
// 决定照片能否被选中
- (BOOL)isAssetCanBeSelected:(PHAsset *)asset {
    return YES;
}
- (void)deleteBtnClik:(UIButton *)sender {
    if ([self collectionView:self.itemView numberOfItemsInSection:0] <= _selectedPhotos.count) {
        [_selectedPhotos removeObjectAtIndex:sender.tag];
        [_selectedAssets removeObjectAtIndex:sender.tag];
        [self.itemView reloadData];
        return;
    }
    
    [_selectedPhotos removeObjectAtIndex:sender.tag];
    [_selectedAssets removeObjectAtIndex:sender.tag];
    [_itemView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [self->_itemView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [self->_itemView reloadData];
    }];
    self.sectionView.photoCount.text = [NSString stringWithFormat:@"%lu/%ld",(unsigned long)_selectedPhotos.count,(long)_maxSelected];
}


-(void)photoSave:(UIButton *)sender{
    NSLog(@"保存图片");
    [self uploadImage];
}

@end
